package com.gonsin.license;


import com.gonsin.base.ResponseResult;
import com.gonsin.license.po.ModifyAuthExpirationTimePo;
import com.gonsin.license.processors.LicenseExtraService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.gonsin.license.LicenseResult.LICENSE_FAIL_8;
import static com.gonsin.license.LicenseResult.SUCCESS;

@RequestMapping("")
@Controller
//@Api(tags = "授权相关接口")
//@ApiIgnore
@Slf4j
public class LicenseController {

    @Autowired LicenseConfig licenseConfig;

    @Autowired private LicenseExtraService licenseExtraService;
    /**
     * 授权页面
     */
//    @ApiOperation("授权页面")
//    @RequestMapping(value = {"/license"}, method = RequestMethod.GET)
//    public ModelAndView license(HttpServletRequest request, Model model){
//
//        String device = licenseConfig.getDevice();
//        String uuid = licenseConfig.getUuid();
//        model.addAttribute("device", device);
//        model.addAttribute("uuid", uuid);
//
//        return new ModelAndView("license", "model", model);
//    }

    @RequestMapping(value = {"/api/license/modifyAuthExpirationTime"}, method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult<Void> modifyAuthExpirationTime(@RequestBody ModifyAuthExpirationTimePo po) throws Exception {
        po.validate();
        licenseConfig.modifyAuthExpirationTime(po.getDate());
        return ResponseResult.simpleResult();
    }

    @RequestMapping(value = {"/license"}, method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult<LicenseResponse> license(){
        LicenseResponse response = new LicenseResponse();
        response.setDevice(GLicenseAutoSelector.DEVICE);
        response.setUuid(licenseConfig.getUuid());
        response.setExtra(licenseExtraService.getExtra());
        response.setVersion(licenseExtraService.getVersion());
        ResponseResult result = ResponseResult.simpleResult();
        if(licenseConfig.isLicensed()){
            Map<String,Object> licenseInfo = new HashMap<>();
            try {
                licenseInfo = licenseConfig.getLicenseFileInfo();
                response.setDate(licenseInfo.get("validate").toString());
            } catch (Exception e){
                log.error("获取授权信息失败,读出的数据为:{}",licenseInfo);
                e.printStackTrace();
            }
            response.setStatus(SUCCESS);
            result.setState(SUCCESS);
            result.setData(response);
            return result;
        }
        result.setState(LICENSE_FAIL_8);
        result.setData(response);
        return result;
    }

    /**
     * 上传授权文件
     *
     */
//    @ApiOperation("上传授权文件")
    @RequestMapping(value = {"/api/upload_license"}, method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult<Void> license(@RequestParam("file") MultipartFile licenseFile) throws IOException {

        File tempFile = new File(licenseConfig.getFilePath() + File.separator + RandomStringUtils.random(32, true, true));

        if(tempFile.exists()){
            tempFile.delete();
        }
        tempFile.createNewFile();
        licenseFile.transferTo(tempFile);

        int result = 0;
        try {
            result = licenseConfig.validateLicenseFile(tempFile);
            tempFile.delete();
        } catch (Exception e) {
            log.error(e.toString(), e);
            result = LicenseResult.LICENSE_FAIL_3;
        }
        return ResponseResult.simpleResult(result);
    }


    /**
     * 在线授权
     */
//    @ApiOperation("在线授权")
    @RequestMapping(value = {"/api/license/online"}, method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult<Void> licensed(@RequestParam("code") @ApiParam("授权码") String code) {

        code = code.toUpperCase();

        // 连接到授权服务器检验是否授权
        int result = licenseConfig.validateLicenseOnline(code);
//        return ResultBean.newResult(LicenseResult.SUCCESS);
        return ResponseResult.simpleResult(result);
    }


    /**
     * 查看是否已授权
     */
    @ApiOperation("查看是否已授权")
    @RequestMapping(value = {"/api/licensed"}, method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult<Boolean> licensed() {
        return ResponseResult.result(licenseConfig.isLicensed());
    }

}
